﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace JsonCodeGenerator
{
    /// <summary>
    /// 特性添加
    /// </summary>
    internal class AttributeRewriter : CSharpSyntaxRewriter
    {
        [JsonPropertyName("")]
        private readonly string _attributeName;

        public AttributeRewriter(string attributeName)
        {
            _attributeName = attributeName;
        }

        public override SyntaxNode? VisitPropertyDeclaration(PropertyDeclarationSyntax node)
        {
            // 在属性前面添加特性标签节点
            var arrtibuteText = string.Format(_attributeName, node.Identifier.ValueText);
            var attribute = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(arrtibuteText));
            var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attribute));

            // 更新属性节点，将特性标签列表添加到属性声明前面
            var updatedNode = node.WithAttributeLists(node.AttributeLists.Insert(0, attributeList));
            return base.VisitPropertyDeclaration(updatedNode);
        }
    }
}
